#include "dl.h"

struct ListNode* creat_node(SLdata x)
{
    struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
    node->prev=NULL;
    node->next=NULL;
    node->val=x;
    return node;
}
void init(LIST ** head)
{
    *head = (struct ListNode*)malloc(sizeof(struct ListNode));
    (*head)->next =(*head);
    (*head)->prev = (*head);
    (*head)->val = -1;
}
void pushback(struct ListNode* head,SLdata x)//尾插
{
    assert(head);
    LIST* cur = head;
    LIST* newnode = creat_node(x);
    cur = cur->prev;
    cur->next = newnode;
    newnode->next = head;
    newnode->prev = cur;
    head->prev = newnode;
}


void pushfront(struct ListNode* head,SLdata x)
{
    assert(head);
    LIST* cur = head->next;
    LIST* newnode = creat_node(x);
    cur->prev = newnode;
    newnode->next = cur;
    newnode->prev = head;
    head->next = newnode;
}
void SLprint(struct ListNode* head)
{
    assert(head);
    assert(head->next!=head);
    printf("guard-> ");
    struct ListNode* cur = head->prev;
    while (cur!=head)
    {
        printf("%d->",cur->val);
        cur = cur->prev;
    }
    printf("\n");
}
void popback(struct ListNode* head)
{
    assert(head);
    assert(head->next!=head);
    struct ListNode *cur = head->prev;
    struct ListNode * fir = cur->prev;
    fir->next = head;
    head->prev = fir;
    free(cur);
}
void popfront(struct ListNode* head)
{
    assert(head);
    assert(head->next!=head);
    struct ListNode *cur = head->next;
    struct ListNode * sec = cur->next;
    head->next = sec;
    sec->prev = head;
    free(cur);
}
struct ListNode* SLfind(struct ListNode* head,SLdata x)
{
    assert(head);
    assert(head->next!=head);
    struct ListNode *cur = head->next;
    while(head != cur)
    {
        if(cur->val==x)
        {
            return cur;
        }
        cur = cur->next;
    }
    return NULL;
}
void intsert_befpos(struct ListNode* pos,SLdata x)
{
    if(!pos)
    {
        perror("the pos is NULL\n");
        return ;
    }
    struct ListNode* pre = pos->prev;
    LIST* newnode = creat_node(x);
    pre->next = newnode;
    newnode->next = pos;
    newnode->prev = pre;
    pos->prev = newnode;
}


void intsert_aftpos(struct ListNode* pos,SLdata x)
{
    if(!pos)
    {
        perror("the pos is NULL\n");
        return ;
    }
    struct ListNode* sec = pos->next;
    LIST* newnode = creat_node(x);
    sec->prev = newnode;
    newnode->next = sec;
    newnode->prev = pos;
    pos->next = newnode;
}